class Solution
{
public:
    string repeatLimitedString(string s, int repeatLimit)
    {
        vector<int> charCount(26, 0);
        for (char c : s)
        {
            ++charCount[c - 'a'];
        }
        char last = 0;
        int lastCount = 0;
        string result;
        while (true)
        {
            char c = 'z';
            for (c = 'z'; c >= 'a'; --c)
            {

                if (charCount[c - 'a'] == 0)
                {
                    continue;
                }
                if (c == last)
                {
                    if (lastCount == repeatLimit)
                    {
                        continue;
                    }
                    else
                    {
                        --charCount[c - 'a'];
                        result.append(1, c);
                        ++lastCount;
                        break;
                    }
                }
                else
                {
                    --charCount[c - 'a'];
                    result.append(1, c);
                    last = c;
                    lastCount = 1;
                    break;
                }
            }
            if (c < 'a')
            {
                break;
            }
        }
        return result;
    }
};